import pandas as pd
import numpy as np

# 索引的堆叠
# --  stack()函数
# --  unstack()函数
data = np.random.randint(0,100,(6,6))
index = [
    ['1班','1班','1班','2班','2班','2班'],
    ['小白','小黑','小红','小白','小黑','小红']
]
columns = [
    ['期中','期中','期中','期末','期末','期末'],
    ['语文','数学','英语','语文','数学','英语'],
]
df = pd.DataFrame(data,index=index,columns=columns)
print(df)

# stack()函数:将列索引变成行索引
print('\n-- stack()函数')
print(df.stack(future_stack=True))     # 默认是将最里层的列索引变成行索引
print("\n")
print(df.stack(level=-1,future_stack=True))
print("\n")
print(df.stack(level=1,future_stack=True))
print("\n")
print(df.stack(level=0,future_stack=True))

print("\n")

# unstack()函数:使用unstack（）的时候，level等于哪一个，哪一个就消失，出现在列里

print('\n-- unstack()函数')
print(df.unstack())
print("\n")
print(df.unstack(level=-1))
print("\n")
print(df.unstack(level=1))
print("\n")
print(df.unstack(level=0))

# 使用fill_value参数，可以填充缺失值
print("\n")
data= np.random.randint(10,100,size=(6,6))
index = [
    ['1班','1班','1班','2班','2班','2班'],
    ['小白','小黑','小红','小紫','小黄','小绿']
]
columns = [
    ['期中','期中','期中','期末','期末','期末'],
    ['语文','数学','英语','物理','化学','生物']
]
df3 = pd.DataFrame(data,index=index,columns=columns)
print(df3)

print(df3.unstack(fill_value=0))










